<template>
  <div class="node">
    <DoubleSearch
      @sendInfo="receiveInfo"
      :AllTitle="{ searchTitle: '点位搜索:', status: '区域搜索:' }"
      :taskSatusList="taskSatusList"
    />
    <div class="list">
      <el-row>
        <el-col :span="4"
          ><el-button icon="iconfont icon-jiahao" type="warning" @click="newCreate"
            >新建</el-button
          ></el-col
        >
      </el-row>
      <el-table
        ref="singleTable"
        :data="regionInfo.currentPageRecords"
        highlight-current-row
        center
        style="width: 100%"
      >
        <el-table-column align="center" label="序号" width="150" type="index" height="45">
        </el-table-column>
        <el-table-column align="center" property="name" label="点位名称" width="220">
        </el-table-column>
        <el-table-column align="center" property="region.name" label="所在区域" width="200">
        </el-table-column>
        <el-table-column align="center" property="businessType.name" label="商圈类型" width="200">
        </el-table-column>
        <el-table-column align="center" property="ownerName" label="合作商" width="240">
        </el-table-column>
        <el-table-column align="center" property="addr" label="详细地址" width="240">
        </el-table-column>
        <el-table-column align="center" label="操作" width="400">
          <template slot-scope="{ row }">
            <el-button type="info" icon="el-icon-search" size="mini" @click.native="seeRegion(row)"
              >查看详情</el-button
            >
            <el-button size="mini" type="primary" icon="el-icon-edit" @click.native="editInfo(row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click.native="deleteInfo(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :searchTaskList="regionInfo"
        @currentSizeChange="(value) => (nodeSearchParams.pageSisubmitFormze = value)"
        @currentPageChange="(value) => (nodeSearchParams.pageIndex = value)"
      />
      <!-- // 弹窗 -->
      <!-- // 新建// 修改 -->
      <Dialog :dialogVisibleInfo="dialogVisibleEdit" @dialogClose="dialogCloseEdit">
        <template #body>
          <el-form
            ref="ruleFormEdit"
            :model="ruleFormEdit"
            :rules="rulesEdit"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="区域名称" prop="name">
              <el-input v-model="ruleFormEdit.name" placeholder="请输入区域名称"></el-input>
            </el-form-item>
            <el-form-item label="所在区域:" prop="regionId">
              <el-select v-model="ruleFormEdit.regionId" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in taskSatusList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属商圈:" prop="businessId">
              <el-select v-model="ruleFormEdit.businessId" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in businessList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="归属合作商:" prop="ownerId">
              <el-select v-model="ruleFormEdit.ownerId" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in ownerList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="详细地址:" prop="areaCode">
              <el-cascader
                v-model="ruleFormEdit.areaCode"
                :options="areaOptions"
                :props="{ expandTrigger: 'hover', value: 'label' }"
                @change="handleChange"
                style="width: 100%"
                clearable
              ></el-cascader>
            </el-form-item>
            <el-form-item label=" " prop="addr">
              <el-input type="textarea" v-model="ruleFormEdit.addr"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm">确认</el-button>
              <el-button @click="dialogVisibleEdit.dialogVisible = false">取消</el-button>
            </el-form-item>
          </el-form>
        </template>
      </Dialog>
      <!-- 查看详情 -->
      <Dialog :dialogVisibleInfo="dialogVisibleDetails">
        <template #body>
          <el-table
            ref="singleTable"
            :data="detailsList"
            highlight-current-row
            center
            style="width: 100%"
          >
            <el-table-column align="center" label="序号" type="index" width="60" height="45">
            </el-table-column>
            <el-table-column align="center" property="innerCode" label="机器编号">
            </el-table-column>
            <el-table-column align="center" label="设备状态"
              ><template slot-scope="{ row }">
                {{ vmStatusObj[row.vmStatus] }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="最后一次供货时间"
              ><template slot-scope="{ row }">
                {{ row.lastSupplyTime.replace('T', ' ') }}
              </template></el-table-column
            >
          </el-table>
        </template>
      </Dialog>
    </div>
  </div>
</template>

<script>
import {
  regionSearchAPI,
  nodeSearchAPI,
  businessTypeAPI,
  partnerSearchAPI,
  addNodeAPI,
  nodeDatailsAPI,
  repairNodeAPI
} from '@/api'
import { regionData, CodeToText } from 'element-china-area-data'
export default {
  name: 'Node',
  data() {
    return {
      // 售货机状态
      vmStatusObj: {
        0: '未投放',
        1: '运营',
        3: '撤机'
      },
      // 获取区域数据的参数-点位管理
      regionInfoParams: {
        pageIndex: 1,
        pageSize: 500
      },
      // 页码
      nodeSearchParams: {
        pageIndex: 1,
        pageSize: 10
      },
      // 获取区域搜索栏-点位管理,// 新建: 所在区域列表
      taskSatusList: [],
      // 渲染列表的点位搜索
      regionInfo: {
        currentPageRecords: []
      },
      // 头部搜索返回值
      searchReceiveInfo: {},
      // 修改区域的弹窗
      dialogVisibleEdit: {
        dialogTitle: '新增点位',
        dialogVisible: false,
        dialogWidth: '30%'
      },
      // 详情页的弹出框
      dialogVisibleDetails: {
        dialogTitle: '点位详情',
        dialogVisible: false,
        dialogWidth: '30%'
      },
      // 所属商圈
      businessList: [],
      // 归属合作商
      ownerList: [],
      // 地区选择的数据
      areaOptions: regionData,
      // 获取到的点位详情数据
      detailsList: [],
      // 新建的表格数据以及校验规则
      // 修改区域的参数
      ruleFormEdit: {
        name: '',
        regionId: '',
        businessId: null,
        ownerId: null,
        areaCode: [],
        addr: '',
        createUserId: 1,
        ownerName: ''
      },
      // 校验规则
      rulesEdit: {
        name: [{ required: true, message: '请输入区域名称', trigger: 'blur' }],
        regionId: [{ required: true, message: '不能为空', trigger: 'blur' }],
        businessId: [{ required: true, message: '不能为空', trigger: 'blur' }],
        ownerId: [{ required: true, message: '不能为空', trigger: 'blur' }],
        areaCode: [{ required: true, message: '不能为空', trigger: 'blur' }],
        addr: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      // 判断修改和新建状态下的弹框提交事件
      idSelset: ''
    }
  },
  created() {
    this.fetchRegionSearch()
    this.fetchnodeSearchInfo(this.nodeSearchParams)
  },
  methods: {
    // 接收搜索的参数
    receiveInfo(value) {
      this.searchReceiveInfo = value
      this.nodeSearchParams.pageIndex = 1 // 每次搜索页面必为1
      this.fetchnodeSearchInfo({ ...this.nodeSearchParams, ...this.searchReceiveInfo })
    },
    async fetchRegionSearch() {
      // 获取区域搜索栏-点位管理
      const res = await regionSearchAPI(this.regionInfoParams)
      this.taskSatusList = res.data.currentPageRecords
      // 获取商圈列表
      const res1 = await businessTypeAPI()
      this.businessList = res1.data
      // 合作商搜索
      const res2 = await partnerSearchAPI(this.regionInfoParams)
      this.ownerList = res2.data.currentPageRecords
    },
    // 获取渲染列表的数据
    async fetchnodeSearchInfo(data) {
      const res = await nodeSearchAPI(data)
      res.data.currentPageRecords.forEach((item) => {
        item.addr = item.addr.split('-').at(-1)
      })
      this.regionInfo = res.data
    },
    // 新增点位的弹窗
    async newCreate() {
      this.dialogVisibleEdit.dialogTitle = '新增点位'
      this.dialogVisibleEdit.dialogVisible = true
    },
    // 新建/修改的确认操作
    submitForm() {
      this.$refs.ruleFormEdit.validate(async (valid) => {
        if (!valid) return
        if (!this.idSelset) {
          const addr = `${this.ruleFormEdit.areaCode.join('-')}-${this.ruleFormEdit.addr}` // 详细地址最后提交数据
          try {
            await addNodeAPI({
              ...this.ruleFormEdit,
              addr,
              ownerName: this.ownerList.filter((item) => item.id === this.ruleFormEdit.ownerId)[0]
                .name,
              areaCode: +Object.keys(CodeToText).find(
                (item) => CodeToText[item] === this.ruleFormEdit.areaCode.at(-1)
              )
            })
            this.$message({
              type: 'success',
              message: '新增成功',
              offset: 75
            })
            this.dialogVisibleEdit.dialogVisible = false
            this.fetchnodeSearchInfo(this.nodeSearchParams)
          } catch (error) {
            this.$message({
              type: 'error',
              message: `${error.response.data}`,
              offset: 75
            })
          }
        } else {
          try {
            let NewAreaCode = ''
            if (this.ruleFormEdit.areaCode instanceof Array) {
              NewAreaCode = +Object.keys(CodeToText).find(
                (item) => CodeToText[item] === this.ruleFormEdit.areaCode.at(-1)
              )
            } else {
              NewAreaCode = +Object.keys(CodeToText).find(
                (item) => CodeToText[item] === this.ruleFormEdit.areaCode
              )
            }
            await repairNodeAPI(this.idSelset, {
              ...this.ruleFormEdit,
              ownerName: this.ownerList.filter((item) => item.id === this.ruleFormEdit.ownerId)[0]
                .name,
              areaCode: NewAreaCode
            })
            this.$message({
              type: 'success',
              message: '修改成功',
              offset: 75
            })
            this.dialogVisibleEdit.dialogVisible = false
            this.idSelset = ''
            this.fetchnodeSearchInfo(this.nodeSearchParams)
          } catch (error) {
            this.$message({
              type: 'error',
              message: error.response.data,
              offset: 75
            })
          }
        }
      })
    },
    // cascader选择器的change事件
    handleChange(value) {
      console.log(value)
    },
    // 查看详情
    async seeRegion(row) {
      this.dialogVisibleDetails.dialogVisible = true
      const res = await nodeDatailsAPI(row.id)
      // console.log(res.data)
      this.detailsList = res.data
    },
    // 修改
    editInfo(row) {
      // 赋值给areaCodeSelset
      this.idSelset = row.id
      // console.log(CodeToText[row.areaCode])
      this.dialogVisibleEdit.dialogTitle = '修改点位'
      this.dialogVisibleEdit.dialogVisible = true
      this.ruleFormEdit.name = row.name
      this.ruleFormEdit.regionId = row.regionId
      this.ruleFormEdit.businessId = row.businessId
      this.ruleFormEdit.ownerId = row.ownerId
      this.ruleFormEdit.addr = row.addr
      this.ruleFormEdit.ownerName = row.ownerName
      // 处理区域id的逻辑
      this.ruleFormEdit.areaCode = CodeToText[row.areaCode] // 区域选中值
    },
    // 删除提示
    deleteInfo() {
      this.$notify({
        title: '提示',
        message: '演示系统，不支持此操作',
        type: 'warning',
        offset: 80,
        duration: 2000
      })
    },
    // 弹框的关闭事件
    dialogCloseEdit() {
      this.$refs.ruleFormEdit.resetFields()
      this.ruleFormEdit.ownerName = ''
      this.idSelset = ''
      this.ruleFormEdit = {
        name: '',
        regionId: '',
        businessId: null,
        ownerId: null,
        areaCode: [],
        addr: '',
        createUserId: 1,
        ownerName: ''
      }
    }
  },
  watch: {
    nodeSearchParams: {
      handler() {
        this.fetchnodeSearchInfo({ ...this.nodeSearchParams, ...this.searchReceiveInfo })
      },
      deep: true
    }
  }
}
</script>
<style lang="less" scoped>
.list {
  padding: 20px 15px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 1px 1px 10px rgb(240, 239, 239);
  .el-col {
    margin-bottom: 20px;
  }
  /deep/.el-table th.el-table__cell {
    background-color: rgb(243, 246, 251);
  }
  /deep/tr.el-table__row {
    height: 45px !important;
  }

  /deep/.el-table td.el-table__cell {
    border: none;
    height: 0px;
    padding: 0;
    .el-button {
      height: 30px;
      line-height: 1px;
      margin: 10px 0 10px 10px;
      width: 80px;
    }
    .el-button--info {
      width: 100px;
    }
  }
  /deep/.el-table th.el-table__cell.is-leaf {
    border: none;
  }
  /deep/.el-button--warning {
    background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
    text-align: center;
    .icon-jiahao:before {
      content: '\e726';
      margin-right: 5px;
    }
  }
  /deep/.el-button--info {
    background-color: #fbf4f0 !important;
    border: none;
    color: #333;
  }
  /deep/.el-table::before {
    height: 0;
  }
}
</style>
